package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.OSEnvironment;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> selectTreeNodes(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //根据有无id判断是新增还是修改
        Long id = saveTeachplanDto.getId();
        if (id == null) {
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            Integer integer = getInteger(teachplan);
            teachplan.setOrderby(integer + 1);
            teachplan.setCreateDate(LocalDateTime.now());
            int insert = teachplanMapper.insert(teachplan);
            if (insert < 1) {
                XueChengPlusException.cast("新增失败");
            }
        } else {
            //修改
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplan.setChangeDate(LocalDateTime.now());
            int i = teachplanMapper.updateById(teachplan);
            if (i < 1) {
                XueChengPlusException.cast("修改失败");
            }
        }
    }

    @Transactional
    @Override
    public void deleteTeachplan(Long id) {
        //判断删除的章节的级别
        Teachplan teachplan = teachplanMapper.selectById(id);
        Integer grade = teachplan.getGrade();
        if (grade == 1) {
            //判断下一级是否存在章节
            LambdaQueryWrapper<Teachplan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Teachplan::getParentid, id);
            Integer integer = teachplanMapper.selectCount(lambdaQueryWrapper);
            if (integer > 0) {
                //还存在有章节不能删除
                XueChengPlusException.cast("该章节还有小节存在，不能删除");
            } else {
                int i = teachplanMapper.deleteById(id);
                if (i < 0) {
                    XueChengPlusException.cast("删除失败");
                }
            }
        }
        if (grade == 2) {
            //删除小节时需要将相关联的视频信息一并删除
            int i = teachplanMapper.deleteById(id);
            LambdaQueryWrapper<TeachplanMedia> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId, id);
            Integer integer = teachplanMediaMapper.selectCount(lambdaQueryWrapper);//查找出数量
            int delete = teachplanMediaMapper.delete(lambdaQueryWrapper);//删除影响的行数
            if (i != 1 || delete != integer) {
                XueChengPlusException.cast("删除失败");
            }
        }
    }

    @Override
    public void move(String moveType, Long id) {
        //判断是否合法（是否是最上面或者最下面）
        boolean extracted = extracted(moveType, id);
        if (!extracted) {
            XueChengPlusException.cast("到顶或到底了");
        }
        if (moveType.equals("moveup")) {
            Teachplan teachplan = teachplanMapper.selectById(id);
            LambdaQueryWrapper<Teachplan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(Teachplan::getParentid, teachplan.getParentid())
                    .lt(Teachplan::getOrderby,teachplan.getOrderby())
                    .orderByDesc(Teachplan::getOrderby)
                    .last("LIMIT 1");
            Teachplan teachplan2 = teachplanMapper.selectOne(lambdaQueryWrapper);
            Integer orderby = teachplan.getOrderby();
            Integer orderby2 = teachplan2.getOrderby();
            teachplan.setOrderby(orderby2);
            teachplan2.setOrderby(orderby);
            int i = teachplanMapper.updateById(teachplan);
            int i2 = teachplanMapper.updateById(teachplan2);
            if ((i+i2)<2){
                XueChengPlusException.cast("操作失败");
            }
        }
        if (moveType.equals("movedown")){
            Teachplan teachplan = teachplanMapper.selectById(id);
            LambdaQueryWrapper<Teachplan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(Teachplan::getParentid, teachplan.getParentid())
                    .gt(Teachplan::getOrderby,teachplan.getOrderby())
                    .orderByAsc(Teachplan::getOrderby)
                    .last("LIMIT 1");
            Teachplan teachplan2 = teachplanMapper.selectOne(lambdaQueryWrapper);
            Integer orderby2 = teachplan2.getOrderby();
            Integer orderby = teachplan.getOrderby();
            teachplan.setOrderby(orderby2);
            teachplan2.setOrderby(orderby);
            int i = teachplanMapper.updateById(teachplan);
            int i2 = teachplanMapper.updateById(teachplan2);
            if ((i+i2)<2){
                XueChengPlusException.cast("操作失败");
            }
        }

    }

    @Override
    public Teachplan getTeachplan(Long teachplanMediaId) {
        TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getId, teachplanMediaId));
        Long teachplanId = teachplanMedia.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        return teachplan;
    }

    private boolean extracted(String moveType, Long id) {
        if (moveType.equals("moveup")) {
            Teachplan teachplan = teachplanMapper.selectById(id);
            Integer orderby = teachplan.getOrderby();
            if (orderby == 1) {
                return false;
            } else {
                return true;
            }
        }
        else  {
            Teachplan teachplan = teachplanMapper.selectById(id);
            Integer orderby = teachplan.getOrderby();
            LambdaQueryWrapper<Teachplan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
            int integer = teachplanMapper.selectCount(lambdaQueryWrapper);
            if (integer == orderby) {
                return false;
            } else {
                return true;
            }
        }
    }

    //获取排序的序号
    private Integer getInteger(Teachplan teachplan) {
        LambdaQueryWrapper<Teachplan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
        lambdaQueryWrapper.eq(Teachplan::getGrade, teachplan.getGrade());
        Integer integer = teachplanMapper.selectCount(lambdaQueryWrapper);
        return integer;
    }

}
